<?php

require 'vars.php';
require 'functs.php';

Authenticate();

require 'config.mysql.php';

$link = MySQL_go($mysql_server,$mysql_user,$mysql_pass);
MySQL_set_db($link,$mysql_db);

$userlevel = Get_userlevel($_SESSION[user]);

if ($userlevel > 0) {
	if (isset($_GET[adduser])) {

		$name = mysql_real_escape_string($_POST[name]);
	
		$checkdbusersql = "SELECT `name` FROM `featherchat_users` WHERE `name` = '".$name."'";
		$result = mysql_query($checkdbusersql);
		$checkdbuser = @mysql_result($result,0); // No error needed here since we are hoping for an empty result.

		if (empty($checkdbuser)) {
			if (!empty($_POST[name]) && !empty($_POST[email])) {
				if (($_POST[email] == $_POST[email2]) && ($_POST[password] == $_POST[password2])) {
					if (empty($_POST[password])) { $password = Rand_pass(); }
					else { $password = $_POST[password]; }

					$email_configsql = "SELECT `email_user`,`email_pass`,`email_host`,`email_port`,`featherchataddr` FROM `featherchat_settings`";
					$result = mysql_query($email_configsql) or die ('Unable to get e-mail info.'.mysql_error());
					$email_config = mysql_fetch_assoc($result);

					Add_user($email_config,$_POST[email],$_SESSION[user],$_POST[name],$password);
					echo "<br />";
					Home_link();
				}
				else { echo "Password or e-mail mismatch."; }
			}
			else { echo "Required field left blank."; }
		}
		else { echo "User ".$_POST[name]." already exists!"; }
	}
	elseif (isset($_GET[deluser])) {
	
		$user = mysql_real_escape_string($_POST[user]);

		$checkdbusersql = "SELECT `name` FROM `featherchat_users` WHERE `name` = '".$user."'";
		$result = mysql_query($checkdbusersql);
		$checkdbuser = mysql_result($result,0) or die ("No such user.");

		if (!empty($checkdbuser)) { // Verify that the user still exists, incase they were already removed between this menu and the last, perhaps by another admin.
			$deletesql = "DELETE FROM `featherchat_users` WHERE `name` = '".$user."' LIMIT 1";
			mysql_query($deletesql) or die ("Deletion failed.");
			Drop_token($user,"%");
			if ($_POST[delposts] == "on") {
				$deletepostssql = "DELETE FROM `featherchat_messages` WHERE `user` = '".$user."'";
				mysql_query($deletepostssql) or die ("Unable to delete user's posts.");
			}
			?>User removed.<br /><?php Home_link();
		}
	}
}
else { echo "You shouldn't be here..."; }

MySQL_halt($link);